<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket Console</title>
    <style>
        body { font-family: sans-serif; margin: 20px; }
        #log { border: 1px solid #ccc; padding: 10px; height: 300px; overflow-y: scroll; background: #f9f9f9; }
        .log-info { color: #555; }
        .log-send { color: blue; }
        .log-recv { color: green; }
        .log-error { color: red; }
        .input-row { margin-bottom: 10px; }
    </style>
</head>
<body>
<h2>WebSocket 控制台</h2>

<div class="input-row">
    你的账号（userAccount）：
    <input type="text" id="userAccount" placeholder="如 alan">
</div>

<div class="input-row">
    WebSocket 地址（自动拼接参数）：
<!--    <input type="text" id="wsUrl" value="ws://localhost:8880/ws/chat" style="width: 300px;" readonly>-->
    <input type="text" id="wsUrl" value="ws://106.15.238.139:8880/ws/chat" style="width: 300px;" readonly>
    <button onclick="connect()">连接</button>
    <button onclick="disconnect()">断开</button>
</div>

<div class="input-row">
    目标用户账号：
    <input type="text" id="targetUser" placeholder="如 bob">
</div>

<div class="input-row">
    消息内容：
    <input type="text" id="messageInput" placeholder="输入要发送的消息" style="width: 300px;"
           onkeydown="if(event.key === 'Enter') sendMessage();">
    <button onclick="sendMessage()">发送</button>
</div>

<div class="input-row">
    当前状态：<span id="status">未连接</span>
</div>

<h3>日志：</h3>
<div id="log"></div>

<script>
    let ws = null;

    function log(message, type = 'info') {
        const logDiv = document.getElementById("log");
        const entry = document.createElement("div");
        entry.className = `log-${type}`;
        entry.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
        logDiv.appendChild(entry);
        logDiv.scrollTop = logDiv.scrollHeight;
    }

    function setStatus(statusText) {
        document.getElementById("status").textContent = statusText;
    }

    function connect() {
        const userAccount = document.getElementById("userAccount").value.trim();
        const baseUrl = document.getElementById("wsUrl").value.trim();

        if (!userAccount) {
            log("请先填写你的 userAccount。", "error");
            return;
        }

        const wsFullUrl = `${baseUrl}?userAccount=${encodeURIComponent(userAccount)}`;

        if (ws && ws.readyState === WebSocket.OPEN) {
            log("已经连接，无需重复连接。", "info");
            return;
        }

        try {
            ws = new WebSocket(wsFullUrl);
        } catch (e) {
            log("连接地址格式错误：" + e.message, "error");
            return;
        }

        log(`正在连接到 ${wsFullUrl} ...`, "info");

        ws.onopen = () => {
            log("已连接", "info");
            setStatus("已连接");
            document.getElementById("userAccount").disabled = true;
        };

        ws.onmessage = (event) => {
            log(`收到消息: ${event.data}`, "recv");
        };

        ws.onclose = () => {
            log("连接已关闭", "info");
            setStatus("未连接");
            document.getElementById("userAccount").disabled = false;
        };

        ws.onerror = (event) => {
            log("WebSocket 发生错误", "error");
            console.error("WebSocket error:", event);
            setStatus("错误");
        };
    }

    function disconnect() {
        if (ws) {
            ws.close();
            log("手动断开连接", "info");
            setStatus("未连接");
            document.getElementById("userAccount").disabled = false;
            ws = null;
        } else {
            log("当前未连接", "info");
        }
    }

    function sendMessage() {
        const messageInput = document.getElementById("messageInput");
        const targetUser = document.getElementById("targetUser").value.trim();
        const message = messageInput.value.trim();

        if (!targetUser) {
            log("请填写目标用户账号。", "error");
            return;
        }
        if (!message) return;
        if (!ws || ws.readyState !== WebSocket.OPEN) {
            log("未连接 WebSocket，无法发送。", "error");
            return;
        }

        const finalMessage = `${targetUser}|${message}`; // 统一格式
        ws.send(finalMessage);
        log(`发送给 ${targetUser}：${message}`, "send");
        messageInput.value = "";
    }
</script>
</body>
</html>
